<!--
 * @Description  : 馆藏资料现状统计
 * @Author       : zhao
 * @Date         : 2022-07-26 09:02:26
 * @LastEditors  : zhao
 * @LastEditTime : 2023-02-04 11:50:25
-->
<template>
    <div class='DistributionChart'>

        <el-row :gutter="15" class="home-card-two mb15">
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                <el-card shadow="hover">
                    <div class="home-card-item">
                        <div style="height: 100%" ref="homeBarRefOne"></div>
                    </div>
                </el-card>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" class="home-media">
                <el-card shadow="hover">
                    <div class="home-card-item">
                        <!-- <div>
                            <el-date-picker v-model="datePicker" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" :size="'default'" unlink-panels
                                @change="getGeoDataYearSAs" />

                        </div> -->
                        <div style="position: absolute" v-if="ishomeBarReftwo">
                            <SvgIcon :name="'ele-ArrowLeftBold'" :size="15" style="position:relative;left:-10px;top:3px"
                                @click="back('年代统计')" class="cursor" />
                        </div>
                        <div style="height: 100%" ref="homeBarReftwo"></div>
                    </div>
                </el-card>
            </el-col>

            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" class="home-media ">
                <el-card shadow="hover" style="height:500px">
                    <div class="home-card-item" style="height:100%">
                        <!-- <div style="height: 100%" ref="homePieReftwo"></div> -->
                        <h3>
                            <span>当前档案借阅量排名</span>
                            <img style="float: right;" src="../../assets/execlDown.png" alt="" @click="dowElecx('档案名')">

                        </h3>
                        <ul class="Rank">
                            <li class="title">
                                <span>排名</span>
                                <span>档案名称</span>
                                <span>借阅量</span>
                            </li>
                            <li v-for="(i, index) in state.RankOne" :key="index" class="content">
                                <span>
                                    <img :src="getAssetsImages('jin.png')" alt="" v-if="index === 0">
                                    <img :src="getAssetsImages('yin.png')" alt="" v-else-if="index === 1">
                                    <img :src="getAssetsImages('tong.png')" alt="" v-else-if="index === 2">
                                    <span v-else>
                                        {{ index + 1 }}
                                    </span>
                                </span>
                                <span class="ellipsis" style="width: calc(100% - 50px)">
                                    <a href="javascript:void(0)" class="ellipsis" :title="i.title">{{ i.title }}</a>

                                </span>
                                <span>{{ i.numbers }}</span>
                            </li>
                        </ul>
                    </div>
                </el-card>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" class="home-media">
                <el-card shadow="hover" style="height:500px">
                    <div class="home-card-item" style="height:100%">
                        <!-- <div style="height: 100%" ref="homePieReftwo"></div> -->
                        <h3>
                            <span>当前档案资料类别排名</span>

                            <img style="float: right;" src="../../assets/execlDown.png" alt="" @click="dowElecx('类别')">


                        </h3>
                        <ul class="Rank">
                            <li class="title">
                                <span>排名</span>
                                <span>资料类别</span>
                                <span>借阅量</span>
                            </li>
                            <li v-for="(i, index) in state.RankTwo" :key="index" class="content">
                                <span>
                                    <img :src="getAssetsImages('jin.png')" alt="" v-if="index === 0">
                                    <img :src="getAssetsImages('yin.png')" alt="" v-else-if="index === 1">
                                    <img :src="getAssetsImages('tong.png')" alt="" v-else-if="index === 2">
                                    <span v-else>
                                        {{ index + 1 }}
                                    </span>
                                </span>
                                <span class="ellipsis" style="width: calc(100% - 50px)">
                                    <a href="javascript:void(0)" class="ellipsis" :title="i.category">{{ i.category
                                    }}</a>

                                </span>
                                <span>{{ i.numbers }}</span>
                            </li>
                        </ul>
                    </div>
                </el-card>
            </el-col>

            <!-- <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" class="home-media">
                <el-card shadow="hover">
                    <div class="home-card-item">
                        <div style="height: 100%" ref="homePieRefTwo"></div>
                    </div>
                </el-card>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" class="home-media">
                <el-card shadow="hover">
                    <div class="home-card-item">
                        <div style="height: 100%" ref="homePieRefThree"></div>
                    </div>
                </el-card>
            </el-col> -->
        </el-row>


        <vue3-json-excel style="display: none;" :json-data="state.execl_data" :fields="state.execl_fields"
            :name="state.execl_name" ref="downexcel">
        </vue3-json-excel>
        {{ state.execl_name }}
    </div>
</template>

<script setup lang='ts'>
import * as echarts from 'echarts';
import { toRefs, reactive, defineComponent, onMounted, ref, watch, nextTick, onActivated } from 'vue';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { useTagsViewRoutes } from '/@/stores/tagsViewRoutes';
import { useChart } from '/@/stores/chart';
import zpublic from '/@/utils/public.ts';

const { getGeoDataSA, getGeoDataYearSA, getBrowsingNumberSA, getBrowsingNumberCategorySA, yearOnYearAmplificationEchartsYData, GetGeoDataByYearSA } = useChart();
//图实例
let global: any = {
    barChartOne: null, //柱状图
    barChartTwo: null, //柱状图
    barChartThree: null, //柱状图
    homePieRefOne: null, //饼状图
    homePieRefTwo: null, //饼状图
    homePieRefThree: null, //饼状图
    dispose: [null, '', undefined],
};
//echarts图
const downexcel = ref()

//定义数据间隔
const dataInterval = [0, 10, 30, 50, 200, 1000, 5000, 12000];


const state = reactive({
    myCharts: [],
    charts: {
        theme: '',
        bgColor: '',
        color: '#303133',
    },
    formline: {
        searchDateBegin: null,
        searchDateEnd: null,
        area: null,
        profession: null,
    },
    datepicker: [],
    area: [],
    profession: "",
    options: [],
    professionData: <any>[],

    RankOne: <any>[],//排行 CS当前借阅量--按档案名称分布
    RankTwo: <any>[],//排行 CS当前借阅量--按档案名称分布

    execl_data: <any>[],//数据exlec
    execl_fields: <any>[],//数据exlec
    execl_name: "",//数据exlec

    geoCount: 0,
    nameCount: 0,

    ylabel: <any>[],//y轴刻度
});


const storesTagsViewRoutes = useTagsViewRoutes();
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const { isTagsViewCurrenFull } = storeToRefs(storesTagsViewRoutes);

const colorList = zpublic.chartColor


// 柱状图 当前馆藏资料总量统计-类型统计
const homeBarRefOne = ref();
const initBarChart = (data: any) => {
    // state.ylabel = yearOnYearAmplificationEchartsYData(data, "yValue")

    if (!global.dispose.some((b: any) => b === global.barChartOne)) global.barChartOne.dispose();
    global.barChartOne = <any>echarts.init(homeBarRefOne.value, state.charts.theme);

    const option = {
        backgroundColor: state.charts.bgColor,
        title: {
            text: '当前馆藏资料总量统计-类型统计',
            x: 'left',
            textStyle: { fontSize: '15', color: state.charts.color },
        },
        tooltip: {
            trigger: 'axis',
            // axisPointer: {
            //     type: 'cross'
            // },
            formatter: (val: any) => {
                let num = val[0].data.oldVal
            
                let text = "类别：" + val[0].name + "<br />" + "数量：" + num
                return text
            }
        },

        xAxis: {
            type: 'category',
            axisLabel: { interval: 0, rotate: 30 }
        },
        yAxis: {
            type: 'value',
            splitNumber: 5,
            interval:3000,
            axisLabel: {

                formatter: function (v: any) {

                    let item = ''
                    if(v===0){
					item='0'
                    }else if(v==3000){
                        item = '10'
                    }
                    else if (v == 6000) {
                        item = '2500'
                    }
                    else if (v == 9000) {
                        item = '5000'
                    }
                    // else if (v == 12000) {
                    //     item = '200'
                    // }
                    
                    // else if (v == 12000) {
                    //     item = '300'
                    // }
                    // else if (v == 15000) {
                    //     item = '500'
                    // }else if(v==24000){
                    //     item = '1000'
                    // }else if(v==159000){
                    //     item = '10000'
                    // }
                   
                    else if (v == 12000) {      
                        item = '7500'
                    }else if(v==15000){
                        item = '10000'
                    }else if(v==18000){
                        item = '18000'
                    }
                     else {
                        item = v
                    }
                    return item

                },

            }
        },
        // yAxis: {
        //     type: 'value',
        //     min: 0,
        //     splitLine: { show: false },
        //     interval: state.ylabel[2],
        //     splitNumber: 5,
        //     axisLabel: {
        //         formatter: (v: any, ix: any) => {
        //             let vl
        //             switch (ix) {
        //                 case 0: vl = state.ylabel[0]
        //                     break;
        //                 case 1: vl = state.ylabel[1]
        //                     break;
        //                 case 2: vl = state.ylabel[2]
        //                     break;
        //                 case 3: vl = state.ylabel[3]
        //                     break;
        //                 case 4: vl = state.ylabel[4]
        //                     break;
        //                 case 5: vl = state.ylabel[5]
        //                     break;
        //             }
        //             return vl
        //         }
        //     }
        // },

        series: [
            {

                type: 'bar',
                itemStyle: {
                    color: function (params: any) {
                        return colorList[params.dataIndex];
                    },
                },


            }
        ],
        dataset: {
            // 这里指定了维度名的顺序，从而可以利用默认的维度到坐标轴的映射。
            // 如果不指定 dimensions，也可以通过指定 series.encode 完成映射。
            dimensions: ["profession", "yValue"],

            // source: data,
            source:enlargeYData(data,"yValue") ,
        },
        toolbox: {
            // show: true,
            right: "20",
            feature: {
                saveAsImage: {
                    show: true,
                },

                myExcel: {
                    show: true,
                    title: "导出Excel",
                    icon: "image://",
                    onclick: (option: any) => {
                        state.execl_fields = {
                            类别: 'profession',
                            数量: 'yValue',
                        }
                        state.execl_name = "当前馆藏资料总量类别统计"
                        state.execl_data = data
                        setTimeout(() => {

                            downexcel.value.generate()
                        }, 100);
                    },
                },
            },
        },
    };

    (<any>global.barChartOne).setOption(option);
    (<any>state.myCharts).push(global.barChartOne);
};


// 柱状图 当前馆藏资料总量统计-年代统计
const homeBarReftwo = ref();
const initBarChart2Title = ref("当前馆藏资料总量统计-年代统计")
let ishomeBarReftwo = ref(false)
const initBarChart2 = (data: any) => {
    if (!global.dispose.some((b: any) => b === global.barChartTwo)) global.barChartTwo.dispose();
    global.barChartTwo = <any>echarts.init(homeBarReftwo.value, state.charts.theme);

    const option = {
        backgroundColor: state.charts.bgColor,
        title: {
            text: initBarChart2Title.value,
            x: 'left',
            textStyle: { fontSize: '15', color: state.charts.color },
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            },
            formatter: (val: any) => {
                let text = "年代：" + val[0].name + "<br />" + "数量：" + val[0].data.value
                return text
            }
        },
        xAxis: {
            type: 'category',
            axisLabel: { interval: 0, rotate: 30 }
        },
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: [
            {

                type: 'bar'
            }
        ],
        dataset: {
            // 这里指定了维度名的顺序，从而可以利用默认的维度到坐标轴的映射。
            // 如果不指定 dimensions，也可以通过指定 series.encode 完成映射。
            dimensions: ["key", "value"],

            source: data,
        },
        toolbox: {
            // show: true,
            right: "20",
            feature: {
                saveAsImage: {
                    show: true,
                },

                myExcel: {
                    show: true,
                    title: "导出Excel",
                    icon: "image://",
                    onclick: (option: any) => {
                        state.execl_fields = {
                            年代: 'key',
                            数量: 'value',
                        }
                        state.execl_name = "当前馆藏资料总量年代统计"
                        state.execl_data = data
                        setTimeout(() => {

                            downexcel.value.generate()
                        }, 100);
                    },
                },
            },
        },
    };
    (<any>global.barChartTwo).setOption(option);
    (<any>state.myCharts).push(global.barChartTwo);
    (<any>global.barChartTwo).on('click', (params: any) => {

        if (!ishomeBarReftwo.value) {
            let year = params.name.split('-')
            GetGeoDataByYearSA({ SearchDateBegin: year[0], SearchDateEnd: year[1] }).then((res) => {
                ishomeBarReftwo.value = true
                initBarChart2(res.data);
            })
        }


    })
};


const getAssetsImages = (name: any) => {
    return new URL(`/src/assets/${name}`, import.meta.url).href;
}


//查询
const onSubmit = () => {

    getGeoDataSA().then((res) => {
        initBarChart(res.data);
    })
    getGeoDataYearSA({}).then((res) => {
        initBarChart2(res.data);
    })


    getBrowsingNumberSA({ PageSize: 50, PageIndex: 1 }).then((res) => {
        state.RankOne = res.data
        state.geoCount = res.count
    })


    getBrowsingNumberCategorySA({ PageSize: 50, PageIndex: 1 }).then((res) => {
        state.RankTwo = res.data
        state.nameCount = res.count
    })

}

//下载elecx
const dowElecx = (val: any) => {
    if (val == "类别") {
        getBrowsingNumberCategorySA({ PageSize: state.geoCount, PageIndex: 1 }).then((res) => {
            state.execl_fields = {
                类别: 'category',
                借阅量: 'numbers',
            }
            state.execl_name = "当前档案资料类别排名"
            state.execl_data = res.data
            setTimeout(() => {
                downexcel.value.generate()
            }, 100);
        })
    }
    if (val == "档案名") {
        getBrowsingNumberSA({ PageSize: state.nameCount, PageIndex: 1 }).then((res) => {
            state.execl_fields = {
                档案名称: 'title',
                借阅量: 'numbers',
                档案号: 'sn'
            }
            state.execl_name = "当前档案资料类别排名"
            state.execl_data = res.data
            setTimeout(() => {
                downexcel.value.generate()
            }, 100);
        })
    }


}

// 批量设置 echarts resize
const initEchartsResizeFun = () => {
    nextTick(() => {
        for (let i = 0; i < state.myCharts.length; i++) {
            setTimeout(() => {
                (<any>state.myCharts[i]).resize();
            }, i * 1000);
        }
    });
};


// 批量设置 echarts resize
const initEchartsResize = () => {
    window.addEventListener('resize', initEchartsResizeFun);
};


// 页面加载时
onMounted(() => {
    initEchartsResize();

});

// 由于页面缓存原因，keep-alive
onActivated(() => {
    initEchartsResizeFun();
});


// 监听 vuex 中的 tagsview 开启全屏变化，重新 resize 图表，防止不出现/大小不变等
watch(
    () => isTagsViewCurrenFull.value,
    () => {
        initEchartsResizeFun();

    }
);


// 监听 vuex 中是否开启深色主题
watch(
    () => themeConfig.value.isIsDark,
    (isIsDark) => {
        nextTick(() => {
            state.charts.theme = isIsDark ? 'dark' : '';
            state.charts.bgColor = isIsDark ? 'transparent' : '';
            state.charts.color = isIsDark ? '#dadada' : '#303133';
            onSubmit()

        });
    },
    {
        deep: true,
        immediate: true,
    }
);

const enlargeYData = (data: object[], yvalue: string) => {
    const interval = 3000
    const Yvalue = [0, 10, 2500, 5000, 7500, 10000, 18000, 21000]
    //     console.log(3000+(2500-10)*3000/2490);
    let ceshi = [
        {
            "profession": "区域地质调查",
            "yValue": 1
        },
        {
            "profession": "矿产勘查",
            "yValue": 19
        },
        {
            "profession": "水工环地质勘查",
            "yValue": 27
        },
        {
            "profession": "物化遥勘查",
            "yValue": 51
        },
        {
            "profession": "油气地质",
            "yValue": 110
        },
        {
            "profession": "海洋地质",
            "yValue": 250
        },
        {
            "profession": "地质科研",
            "yValue": 7220
        },
        {
            "profession": "技术方法",
            "yValue": 19500
        },
        {
            "profession": "其他",
            "yValue": 400
        }
    ]

    // console.log(3000/15);
    
    let sdata = [...ceshi]
    data.forEach((e: any) => {
        let num = e[yvalue]
        e.oldVal = num
        // Yvalue.forEach((s,index) => {
        //     if (Yvalue[index] && num > s && num > Yvalue[index]) {
        //          e[yvalue] =( interval*index-1) + (num - s)*(interval/(Yvalue[index]-s))
        //     }
        //  })
         if (num > 0 && num <= 10) {
            e[yvalue] =num*300
        }
        else if (num > 10 && num <= 2500) {
            e[yvalue] =3000+(num-10)*3000/2490
        }
        
        else if (num > 2500 && num <= 5000) {
            e[yvalue] =6000+(num-2500)*(3000/2500)
        }
        else if (num > 5000 && num <= 7500) {
            e[yvalue] =9000+(num-5000)*(3000/2500)
        }
        else if (num > 7500 && num <= 10000) {
            e[yvalue] =12000+(num-7500)*(3000/2500)
        }
        else if (num > 10000 && num <= 18000) {
            e[yvalue] =15000+(num-10000)*(3000/8000)
        }
        // else if (num > 10000 && num <= 20000) {
        //     e[yvalue] =159000+num*(3000/10000)
        // }
        

    });

    return data
}

//自定义y刻度
const ylabel = () => {

}

const back = (type: string) => {
    if (type == "年代统计") {
        getGeoDataYearSA({}).then((res) => {
            ishomeBarReftwo.value = false
            initBarChart2(res.data);
        })

    }
}
</script>
<style lang='scss' scoped>
.home-card-item {
    height: 270px;
    width: 100%;
    overflow: hidden;
    background: white;
}

ul {
    overflow-y: scroll;
    height: 470px;

    li {
        // color: #2b81ff;

        // padding-top: 10px;

        margin: 10px;
        height: 30px;
        display: flex;
        // align-items: center;
        // justify-content: flex-start;

        // font-size: 16px;
        &:nth-child(2n-1) {
            // background: #f6f6f6;
        }

        &:nth-child(2n) {
            // background: white;
        }

        span {
            display: inline-block;
        }

        span:nth-child(1) {
            margin-right: 10px;
            width: 30px;
            text-align: center;
        }

        span:nth-child(2) {

            width: calc(100% - 110px);


        }

        span:nth-child(3) {
            width: 80px;
            text-align: center;
        }

        // span:last-child {
        //     line-height: 26px;
        //     padding-top: 10px;
        // }

        .point {
            background-size: 100% 100%;

            width: 40px;
            height: 40px;
            line-height: 0.503333rem;
            text-align: center;
            color: white;
            margin-bottom: 20px;
        }

        &.content:hover {
            background: #f6f6f6;
        }

    }

    // li:nth-child(1){
    //     span:nth-child(1){
    //         back
    //     }
    // }

    // .content {
    //     height: 130px;
    //     background: var(--el-color-primary-light-9)
    // }
}

.el-card {
    margin-bottom: 10px;
}
</style>